package com.ssyt.examinationsystem.controller;

import com.ssyt.examinationsystem.entity.RightInfo;
import com.ssyt.examinationsystem.entity.RoleInfo;
import com.ssyt.examinationsystem.service.IRightInfoService;
import com.ssyt.examinationsystem.service.IRoleInfoService;
import com.ssyt.examinationsystem.service.impl.RightInfoServiceImpl;
import com.ssyt.examinationsystem.service.impl.RoleInfoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * Servlet implementation class RightInfoController
 */
public class RightInfoController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public RightInfoController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 调用业务查询所有菜单的方法
        IRightInfoService rightService = new RightInfoServiceImpl();
        // 创建一个查询所有角色方法业务方法对象
        IRoleInfoService roleService = new RoleInfoServiceImpl();
        // 获取地址栏的参数值
        String flag = request.getParameter("flag");
        // 获取输出流对象
        PrintWriter out = response.getWriter();
        if ("init".equals(flag)) {
            init(rightService, request, response);
        } else if ("query".equals(flag)) {
            query(rightService, request, response);
        } else if ("grant".equals(flag)) {
            grant(rightService, request, response, out);
        } else if ("initAdd".equals(flag)) {
            initAdd(rightService, request, response);
        } else if ("add".equals(flag)) {
            add(rightService, request, response, out);
        } else if ("genericId".equals(flag)) {
            genericId(rightService, request, response, out);
        } else if ("list".equals(flag)) {
            list(roleService, request, response);
        }

        out.flush();
        out.close();
    }

    /**
     * 查询所有角色授权的方法
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void list(IRoleInfoService roleService, HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 调用角色的查询所有业务方法
        List<RoleInfo> roleList = roleService.getRoleInfos();
        // 将集合保存在请求对象中
        request.setAttribute("roleList", roleList);

        // 转发到WEB-INF/views/right/list.jsp页面
        request.getRequestDispatcher("WEB-INF/views/right/list.jsp").forward(request, response);
    }

    /**
     * 根据父权限编号查询权限编号
     *
     * @param rightService
     * @param request
     * @param response
     * @param out
     */
    private void genericId(IRightInfoService rightService, HttpServletRequest request, HttpServletResponse response,
                           PrintWriter out) {
        String parentId = request.getParameter("parentId");
        String MaxChild = rightService.getMaxRightIdByParentId(parentId);
        String genericId = null;
        if (MaxChild != null) {
            String endString = MaxChild.substring(MaxChild.lastIndexOf("00"));
            Integer number = Integer.valueOf(endString) + 1;
            genericId = parentId + "00" + number;
        } else {
            genericId = parentId + "001";
        }
        out.print(genericId);
    }

    /**
     * 添加权限
     *
     * @param rightService
     * @param request
     * @param response
     * @param out
     * @throws UnsupportedEncodingException
     */
    private void add(IRightInfoService rightService, HttpServletRequest request, HttpServletResponse response,
                     PrintWriter out) throws UnsupportedEncodingException {
        // 获取表单数据
        String rightId = request.getParameter("rightId");
        // 对网页数据进行转码（网页数据使用了encodeURI()操作）
        rightId = URLDecoder.decode(rightId, "UTF-8");

        String parentId = request.getParameter("parentId");
        parentId = URLDecoder.decode(parentId, "UTF-8");

        String rightName = request.getParameter("rightName");
        rightName = URLDecoder.decode(rightName, "UTF-8");

        String rightUrl = request.getParameter("rightUrl");
        rightUrl = URLDecoder.decode(rightUrl, "UTF-8");
        // 创建间权限对象，并封装属性
        RightInfo right = new RightInfo();
        right.setParentId(parentId);
        right.setRightId(rightId);
        right.setRightName(rightName);
        right.setRightUrl(rightUrl);
        // 调用添加权限的业务方法
        int row = rightService.addRightInfo(right);
        if (row > 0) {
            out.print("ok");
        }
    }

    /**
     * 初始化添加权限的方法
     *
     * @param rightService
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void initAdd(IRightInfoService rightService, HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        List<Map<String, Object>> list = rightService.getSysMainMenus();
        request.setAttribute("list", list);
        request.getRequestDispatcher("WEB-INF/views/right/add.jsp").forward(request, response);
    }

    /**
     * 处理授权的方法
     *
     * @param rightService
     * @param request
     * @param response
     * @param out
     */
    private void grant(IRightInfoService rightService, HttpServletRequest request, HttpServletResponse response,
                       PrintWriter out) {
        // 获取地址栏上的参数
        String ids = request.getParameter("ids");
        String roleId = request.getParameter("roleId");
        // 调用授权的业务方法，并判断是否授权成功
        if (rightService.grantRightByRole(roleId, ids)) {
            out.print("<script>alert('授权失败');location.href='roleInfoController?flag=query';</script>");
        } else {
            out.print("<script>alert('授权失败');location.href='roleInfoController?flag=query';</script>");
        }

    }

    /**
     * 查询所有菜单的方法
     *
     * @param rightService
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void query(IRightInfoService rightService, HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取角色编号
        Integer roleId = Integer.valueOf(String.valueOf(request.getParameter("roleId")));
        RoleInfo role = new RoleInfo();
        role.setRoleId(roleId);
        // 调用根据角色编号查询所有主菜单的业务方法
        List<RightInfo> mainMenuByRole = rightService.getMainMenuByRoleId(role);
        // 调用根据角色编号查询所有子菜单的业务方法
        List<RightInfo> childMenuByRole = rightService.getChildMenuByRoleId(role);
        // 把菜单的集合存放在request对象中
        request.setAttribute("mainMenuByRole", mainMenuByRole);
        request.setAttribute("childMenuByRole", childMenuByRole);

        List<Map<String, Object>> mainMenus = rightService.getMainMenus();
        List<Map<String, Object>> childMenus = rightService.getChildMenus();
        // 把菜单的集合存放在request对象中
        request.setAttribute("mainMenus", mainMenus);
        request.setAttribute("childMenus", childMenus);

        request.getRequestDispatcher("WEB-INF/views/right/grant.jsp").forward(request, response);
    }

    /**
     * 初始化查询菜单的方法
     *
     * @param rightService
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void init(IRightInfoService rightService, HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Integer roleId = Integer.valueOf(String.valueOf(request.getSession().getAttribute("roleId")));
        RoleInfo role = new RoleInfo();
        role.setRoleId(roleId);
        // 调用根据角色编号查询所有主菜单的业务方法
        List<RightInfo> mainMenuList = rightService.getMainMenuByRoleId(role);
        // 调用根据角色编号查询所有子菜单的业务方法
        List<RightInfo> childMenuList = rightService.getChildMenuByRoleId(role);
        // 把菜单的集合存放在request对象中
        request.setAttribute("mainMenuList", mainMenuList);
        request.setAttribute("childMenuList", childMenuList);

        request.getRequestDispatcher("WEB-INF/views/main.jsp").forward(request, response);
    }

}
